import { useState, useEffect } from 'react';
import {
  Table,
  Row,
  Col,
  Pagination,
  Space,
  Card,
  Modal as antdModal,
  message,
  Button,
  Tooltip,
  Form,
  InputNumber,
} from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ActionBuilder from './builder/ActionBuilder';
import { useRequest, useIntl, history, useLocation } from 'umi';
import ColumnBuilder from './builder/ColumnBuilder';
import { stringify } from 'query-string';
import Modal from './component/Modal';
import { ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { useSessionStorageState, useToggle, useUpdateEffect } from 'aHooks';
import styles from './index.less';
import SearchBuilder from './builder/SearchBuilder';
import { submitFieldsAdaptor } from './helper';
const Index = () => {
  const [pageQuery, setPageQusery] = useState('');
  const [sortQuery, setSortQuery] = useState('');
  const [searchQuery, setSearchQuery] = useState<string | true>('');
  const [modalVisible, setModalVisible] = useState(false);
  const [modalUri, setModalUri] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [tableColumns, setTableColumns] = useSessionStorageState<BasicListApi.Field[]>(
    'tableKes',
    [],
  );
  const [searchVisible, setSearchVisible] = useToggle(false);
  const [searchForm] = Form.useForm();
  const Intl = useIntl();
  const { confirm } = antdModal;
  const location = useLocation();
  console.log(location);

  const init = useRequest<{ data: BasicListApi.ListData }>((option: any) => {
    const url = `${location.pathname.replace('/basic-list', '')}`;
    if (option === true) {
      return {
        url,
      };
    }
    return {
      // url: `https://public-api-v2.aspirantzhang.com${location.pathname.replace(
      //   '/basic-list',
      //   '',
      // )}?X-API-KEY=antd${pageQuery}${sortQuery}`,
      // params: values,
      // paramsSerializer: (params: any) => {
      //   return stringify(params, { arrayFormat: 'comma', skipEmptyString: true, skipNull: true });
      // },
      url: `${url}?${searchQuery}${pageQuery}${sortQuery}`,
    };
  });

  const request = useRequest(
    (values: any) => {
      message.loading({ content: '加载中...', key: 'process', duration: 0 });
      const { uri, method, ...formValues } = values;
      return {
        url: `https://public-api-v2.aspirantzhang.com${uri}`,
        method,
        data: {
          ...formValues,
          'X-API-KEY': 'antd',
        },
      };
    },
    {
      manual: true,
      onSuccess: () => {
        message.success({
          content: '更新成功',
          key: 'process',
        });
      },
      formatResult: (res: any) => {
        return res;
      },
      throttleInterval: 1000,
    },
  );

  useEffect(() => {
    if (init?.data?.layout?.tableColumn) {
      setTableColumns(ColumnBuilder(init.data.layout.tableColumn, actionHandler));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [init?.data?.layout?.tableColumn]);
  useUpdateEffect(() => {
    init.run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageQuery, sortQuery, location.pathname, searchQuery]);

  useEffect(() => {
    if (modalUri) {
      setModalVisible(true);
    }
  }, [modalUri]);
  // 方法
  function actionHandler(action: BasicListApi.Action, record: BasicListApi.Field) {
    switch (action.action) {
      case 'modal':
        setModalUri(
          (action?.uri || '').replace(/:\w+/g, (item) => {
            return record[item.replace(':', '')];
          }) as string,
        );
        break;
      case 'page': {
        const uri = (action?.uri || '').replace(/:\w+/g, (item) => {
          return record[item.replace(':', '')];
        }) as string;
        history.push(`/basic-list${uri}`);
      }
      case 'reload':
        init.run();
        break;
      case 'delete':
      case 'deletePermanently':
      case 'restore': {
        const operationName = Intl.formatMessage({
          id: `basic-list.list.actionHandler.operation.${action.action}`,
        });
        confirm({
          title: Intl.formatMessage(
            {
              id: 'basic-list.list.actionHandler.confirmTitle',
            },
            {
              operationName,
            },
          ),
          icon: <ExclamationCircleOutlined />,
          content: batchOverviews(Object.keys(record).length ? [record] : selectedRows),
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            return request.run({
              uri: action.uri,
              method: action.method,
              type: action.action,
              ids: selectedRowKeys,
            });
          },
          onCancel() {
            console.log('Cancel');
          },
        });
        break;
      }
      default:
        break;
    }
  }
  const paginationChangeHandler = (page: any, perPage: any) => {
    setPageQusery(`${page}&per_page=${perPage}`);
  };
  const tableChangeHandler = (_: any, __: any, sorter: any) => {
    if (sorter.order === undefined) {
      setSortQuery('');
    } else {
      const time = sorter.order === 'ascend' ? 'asc' : 'desc';
      setSortQuery(`&sort=${sorter.field}&order=${time}`);
    }
  };
  const handleCancel = (reload = false) => {
    setModalVisible(false);
    setModalUri('');
    if (reload) {
      init.run();
    }
  };
  const batchToolbar = () => {
    return (
      selectedRowKeys.length > 0 && (
        <Space>{ActionBuilder(init?.data?.layout?.batchToolBar, actionHandler)}</Space>
      )
    );
  };
  const onFinish = (value: any) => {
    const searchString = stringify(submitFieldsAdaptor(value), {
      arrayFormat: 'comma',
      skipEmptyString: true,
      skipNull: true,
    });
    setSearchQuery(searchString && `&${searchString}`);
  };

  // 组件
  function batchOverviews(dataSource: BasicListApi.Field[]) {
    return (
      <Table
        size="small"
        rowKey="id"
        columns={[tableColumns[0] || {}, tableColumns[1] || {}]}
        dataSource={dataSource}
        pagination={false}
      />
    );
  }
  const searchLayout = () => {
    return (
      searchVisible && (
        <div key="search">
          <Card className={styles.searchForm} key="searchForm">
            <Form onFinish={onFinish} form={searchForm}>
              <Row gutter={24}>
                <Col sm={6}>
                  <Form.Item label="ID" name="id" key="id">
                    <InputNumber keyboard={true} min={1} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                {SearchBuilder(init?.data?.layout?.tableColumn)}
              </Row>
              <Row>
                <Col sm={24} className={styles.textAlignRight}>
                  <Space>
                    <Button type="primary" htmlType="submit">
                      Submit
                    </Button>
                    <Button
                      onClick={() => {
                        setSearchQuery('');
                        searchForm.resetFields();
                      }}
                    >
                      Clear
                    </Button>
                  </Space>
                </Col>
              </Row>
            </Form>
          </Card>
        </div>
      )
    );
  };
  const beforeTableLayout = () => {
    return (
      <Row>
        <Col xs={24} sm={12} />
        <Col xs={24} sm={12} className={styles.tableToolbar}>
          <Tooltip title="search" className={styles.search}>
            <Button
              shape="circle"
              icon={<SearchOutlined />}
              type={searchVisible ? 'primary' : 'default'}
              onClick={() => {
                setSearchVisible.toggle();
              }}
            />
          </Tooltip>
          <Space>{ActionBuilder(init?.data?.layout?.tableToolBar, actionHandler)}</Space>
        </Col>
      </Row>
    );
  };
  const afterTableLayout = () => {
    return (
      <Row>
        <Col xs={17} sm={8} />
        <Col xs={30} sm={16} className={styles.tableToolbar}>
          <Pagination
            total={init?.data?.meta?.total || 0}
            current={init?.data?.meta?.page || 1}
            pageSize={init?.data?.meta?.per_page || 10}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共${total}条`}
            onChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (_selectedRowKeys: any, _selectedRows: any) => {
      setSelectedRowKeys(_selectedRowKeys);
      setSelectedRows(_selectedRows);
    },
  };
  return (
    <PageContainer>
      {searchLayout()}
      <Card>
        {beforeTableLayout()}
        <Table
          rowKey="id"
          dataSource={init?.data?.dataSource}
          columns={tableColumns}
          pagination={false}
          loading={init.loading}
          onChange={tableChangeHandler}
          rowSelection={rowSelection}
        />
        {/* dataSource columns */}
        {afterTableLayout()}
      </Card>
      <Modal modalVisible={modalVisible} handleCancel={handleCancel} modalUri={modalUri} />
      <FooterToolbar>{batchToolbar()}</FooterToolbar>
    </PageContainer>
  );
};
export default Index;
